using Android.App;
using Android.Content;
using Android.OS;
using MauiBuilder.Services;
using Application = Android.App.Application;

namespace MauiBuilder.Platforms.Android
{
    public class AppRestartService : IAppRestartService
    {
        public void RestartApp()
        {
            try
            {
                var context = Application.Context;

                // 方法1: 使用 StartActivity 确保重启
                RestartViaActivity(context);
            }
            catch (Exception ex)
            {
                LogManager.Instance.LogError($"重启失败: {ex.Message}");

            }
        }

        public async Task RestartAppAsync()
        {
            // 显示重启提示
            await ShowRestartNotification();

            // 短暂延迟，让用户看到提示
            await Task.Delay(1000);

            RestartApp();
        }

        private void RestartViaActivity(Context context)
        {
            // 获取启动 Intent
            var intent = context.PackageManager?.GetLaunchIntentForPackage(context.PackageName);
            if (intent != null)
            {
                intent.AddFlags(ActivityFlags.NewTask |
                               ActivityFlags.ClearTask |
                               ActivityFlags.ResetTaskIfNeeded);

                // 添加额外数据确保重新创建
                intent.PutExtra("RESTART_REASON", "user_request");

                // 启动 Activity
                context.StartActivity(intent);

                // 结束当前进程
                FinishActivityAndProcess();
            }
            else
            {
                throw new InvalidOperationException("无法获取启动 Intent");
            }
        }

        private void FinishActivityAndProcess()
        {
            try
            {
                // 结束当前 Activity
                var activity = Platform.CurrentActivity;
                activity?.FinishAffinity();

                // 结束进程
                Java.Lang.JavaSystem.Exit(0);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"结束进程失败: {ex.Message}");
            }
        }

        private async Task ShowRestartNotification()
        {
            try
            {
                // 在主线程显示提示
                await MainThread.InvokeOnMainThreadAsync(async () =>
                {
                    var shell = Shell.Current;
                    if (shell != null)
                    {
                        await shell.DisplayAlert(
                            "重启中",
                            "应用即将重启...",
                            "确定");
                    }
                });
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"显示重启提示失败: {ex.Message}");
            }
        }
    }
}
